//
//  WXApiManager.m
//  SDKSample
//
//  Created by Jeason on 16/07/2015.
//
//

#import "WXApiManager.h"

@implementation WXApiManager

#pragma mark - LifeCycle
+(instancetype)sharedManager {
    static dispatch_once_t onceToken;
    static WXApiManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[WXApiManager alloc] init];
    });
    return instance;
}

- (void)registerWinxin {
    [WXApi startLogByLevel:WXLogLevelNormal logBlock:^(NSString *log) {
        NSLog(@"log : %@", log);
    }];

    
    if ([WXApi registerApp:wei_xin_appID universalLink:wei_xin_Link]) {
        NSLog(@"微信注册成功");
    } else{
        NSLog(@"微信注册失败");
    }
}

#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp {
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        NSString *strMsg,*strTitle = [NSString stringWithFormat:@"支付结果"];
        
        switch (resp.errCode) {
            case WXSuccess:
                strMsg = @"支付结果：成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                [[NSNotificationCenter defaultCenter] postNotificationName:WINXIN_PAY_SUCCESS object:nil];
                break;
                
            default:
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                [[NSNotificationCenter defaultCenter] postNotificationName:WINXIN_PAY_FAILED object:nil];
                break;
        }

        UIAlertController * alert = [UIAlertController alertControllerWithTitle:strTitle message:strMsg preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:action1];
    }else if ([resp isMemberOfClass:[SendAuthResp class]])  {
        NSLog(@"******************获得的微信登录授权******************");
        
        SendAuthResp *aresp = (SendAuthResp *)resp;
        if (aresp.errCode != 0 ) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [QMUITips showError:@"微信授权失败"];
            });
            return;
        }
        //授权成功获取 OpenId
        NSString *code = aresp.code;
        NSLog(@"微信给的code：%@",code);
        [self getWeiXinOpenId:code];
        
        //[self getWeiXinOpenId:code];
    }
}
//通过code获取access_token，openid，unionid
- (void)getWeiXinOpenId:(NSString *)code{
    /*
     appid    是    应用唯一标识，在微信开放平台提交应用审核通过后获得
     secret    是    应用密钥AppSecret，在微信开放平台提交应用审核通过后获得
     code    是    填写第一步获取的code参数
     grant_type    是    填authorization_code
     */
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",wei_xin_appID,@"612d14bfa8eec994202f89f036d4eba2",code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data1 = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        
        if (!data1) {
            [QMUITips showError:@"微信授权失败"];
            return ;
        }
        
        // 授权成功，获取token、openID字典
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"token、openID字典===%@",dic);
        NSString *access_token = dic[@"access_token"];
        NSString *openid= dic[@"openid"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"wxlogSuccess" object:nil userInfo:@{@"openid":openid}];
        //         获取微信用户信息
        //[self getUserInfoWithAccessToken:access_token WithOpenid:openid];
    });
}
- (void)onReq:(BaseReq *)req {

}

- (void)payUsingData:(NSDictionary *)dict {
//    UIViewController * vc = [AppTools zs_getCurrentViewController];
//    [QMUITips showLoadingInView:vc.view];

    PayReq *request = [[PayReq alloc] init];
    request.partnerId = dict[@"partnerid"];
    request.prepayId= dict[@"prepayid"];
    request.package = dict[@"packages"];
    request.nonceStr= dict[@"noncestr"];
    request.timeStamp= [NSString stringWithFormat:@"%@", dict[@"timestamp"]].intValue;
    request.sign= dict[@"sign"];
    NSLog(@"%@   %@    %@    %@   %u    %@",request.package,request.partnerId,request.prepayId,request.nonceStr,(unsigned int)request.timeStamp,request.sign);
    [WXApi sendReq:request completion:^(BOOL success) {
        if (success) {
             NSLog(@"发送成功");
//            [QMUITips hideAllTips];
         }else{
             NSLog(@"发送失败");
             [QMUITips showError:@"微信支付调用失败"];
         }
    }];
 
} //partnerId prepayId package nonceStr timeStamp sign

@end
